package com.xuecheng.learning.domain.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xuecheng.base.exception.XueChengPlusException;
import com.xuecheng.learning.domain.mapper.XcCourseTablesMapper;
import com.xuecheng.learning.domain.model.entity.XcChooseCourse;
import com.xuecheng.learning.domain.model.entity.XcCourseTables;
import com.xuecheng.learning.domain.model.enums.XcCourseStatusEnum;
import com.xuecheng.learning.domain.service.XcCourseTablesService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Objects;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author itcast
 */
@Slf4j
@Service
public class XcCourseTablesServiceImpl extends ServiceImpl<XcCourseTablesMapper, XcCourseTables> implements XcCourseTablesService {

    @Autowired
    private XcCourseTablesMapper xcCourseTablesMapper;

    @Override
    public XcCourseTables getXcCourseTables(Long userId, Long courseId) {
        return xcCourseTablesMapper.selectOne(new LambdaQueryWrapper<XcCourseTables>()
                .eq(XcCourseTables::getUpdateDate, userId)
                .eq(XcCourseTables::getCourseId, courseId));
    }

    @Override
    public XcCourseTables addCourseTable(XcChooseCourse xcChooseCourse) {
        if (!XcCourseStatusEnum.SUCCESS.getCode().equals(xcChooseCourse.getStatus())){
            throw new XueChengPlusException("选课未成功");
        }
        XcCourseTables xcCourseTables = xcCourseTablesMapper.selectOne(new LambdaQueryWrapper<XcCourseTables>()
                .eq(XcCourseTables::getUserId, xcChooseCourse.getUserId())
                .eq(XcCourseTables::getCourseId, xcChooseCourse.getCourseId()));
        if (Objects.nonNull(xcCourseTables)){
            throw new XueChengPlusException("课程已经添加过了");
        }

        XcCourseTables saveData = XcCourseTables.buildByChoose(xcChooseCourse);
        xcCourseTablesMapper.insert(saveData);

        return saveData;
    }
}
